//
//  PersonalInformationViewController.m
//  tryshopping.boss
//
//  Created by Mr.Lee on 16/11/28.
//  Copyright © 2016年 Reabam. All rights reserved.
//


#define KPCellHeight  55   // cell高度
#define KPARROWHEIGHT  13  // 箭头宽
#define KPARROWWIDTH  13    // 箭头高
#define KPARROWRIGHTPADDING  15   // 左边距

#import "PersonalInformationViewController.h"
#import "ZJSwitch.h"
#import "UpYun.h"
#import "VPImageCropperViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIButton+WebCache.h"
#import "ChangeUserNameController.h" //更改用户昵称
#import "ChangePhoneNumController.h" //更改绑定手机
@interface PersonalInformationViewController () <UITableViewDelegate, UITableViewDataSource,VPImageCropperDelegate,UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableV;
/** 数据 */
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) UIImageView *portraitImageView;
@property (nonatomic,strong) UIImagePickerController *ipc;
@property (strong, nonatomic) UIImage *sendImage;
@property (nonatomic, weak) UIImage *setImage;
/** 性别 */
@property (nonatomic, copy) NSString *sexStr;
/** UPYUN的配置由服务端产生 */
@property (nonatomic, strong) NSString *policy;
@property (nonatomic, strong) NSString *signature;
@property (nonatomic, strong) NSString *action;
@end

@implementation PersonalInformationViewController
{
    NSDictionary*dic;;
    UIButton *imageView;
    NSString* headImageUrl;
    NSString*headImage;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = zuiqianhuiColor;
    self.titleArr = @[@"头像", @"姓名", @"性别", @"身份", @"手机号", @"所属品牌"];
    [self setUpTableView];
    self.title = @"账户管理";
    // 更新用户信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upDataUserInfo) name:@"upDataUserInfo" object:nil];
    // 请求数据
    [self requestData1];
    
}

// 刷新用户信息的通知
- (void)upDataUserInfo{
    [self requestData1];
}

-(void)requestData1{
    [MBProgressHUD showIndeterminateHudSub:@"" delay:30 view:self.view];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [HttpRequest requestData1:@"Common/UserInfo" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        NSLog(@"GetUserAuthStatus === %@",severDataDict.dataDict);
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [MBProgressHUD hideProgressHUDInternal:self.view];
                    dic=severDataDict.dataDict;
                    [self.tableV reloadData];
                
                if (Token!=nil) {
                    
                }else{
                    
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                        LoginViewController*detailViewController = [[LoginViewController alloc] init];
                        [self.navigationController pushViewController:detailViewController animated:YES];
                    }
                }
            } else {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSString *subStr = [severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHudSub:subStr view:self.view];
            }
        } else {
            [MBProgressHUD hideProgressHUDInternal:self.view];
            NSString *subStr = [severDataDict.dataDict objectForKey:@"ResultString"];
            [MBProgressHUD showTextHudSub:subStr view:self.view];
        }
    }];
}

- (void)setUpTableView{
    self.tableV.separatorStyle=UITableViewCellSeparatorStyleNone;
//    self.tableV.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
    self.tableV.backgroundColor = zuiqianhuiColor;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{

}
#pragma mark--TableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1 ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.titleArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.textLabel.text = [self.titleArr objectAtIndex:indexPath.row];
    cell.textLabel.font=[UIFont systemFontOfSize:15];
    cell.textLabel.textColor=[UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
    
    
    if ([[self.titleArr objectAtIndex:indexPath.row]isEqualToString:@"头像"]) {
        UIView *lineLabel0=[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.5)];
        lineLabel0.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel0];
        
        UIView *bgView = [[UIView alloc] init];
        bgView.frame = CGRectMake(ScreenWidth-70-40, (80-70)/2,70, 70);
        bgView.backgroundColor =  [UIColor colorWithHexString:@"cccccc" alpha:0.24];
        bgView.layer.cornerRadius = bgView.width * 0.5;
        bgView.layer.masksToBounds = YES;
        [cell.contentView addSubview:bgView];
        
        imageView = [[UIButton alloc]initWithFrame:CGRectMake(2, 2,70-4, 70-4)];
        imageView.layer.masksToBounds = YES;
        NSString *iconImage = [[dic objectForKey:@"userData"] objectForKey:@"headImageUrl"];
        
        NSURL *url = [NSURL URLWithString:iconImage];
        [imageView sd_setImageWithURL:url forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"touxiang_normal"]];
        imageView.layer.cornerRadius = (70-4)/2;
        imageView.userInteractionEnabled=NO;
        [bgView addSubview:imageView];
        
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-KPARROWWIDTH - KPARROWRIGHTPADDING,(80-KPARROWHEIGHT)/2, KPARROWWIDTH, KPARROWHEIGHT);
        [jiantou setImage:[UIImage imageNamed:@"arrow_right"] forState:UIControlStateNormal];
        [cell.contentView addSubview:jiantou];
        
        UIView *lineLabel1=[[UIView alloc] initWithFrame:CGRectMake(10, 80-0.5, ScreenWidth-20, 0.5)];
        lineLabel1.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel1];
        
    }
    if ([[self.titleArr objectAtIndex:indexPath.row]isEqualToString:@"姓名"]) {
        
//        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-205, 0, 160, KPCellHeight)];
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(100, 0, ScreenWidth-138, KPCellHeight)];
        label.text = [[dic objectForKey:@"userData"] objectForKey:@"userName"];
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor;
        label.font=[UIFont systemFontOfSize:15.0];
        [cell.contentView addSubview:label];
        
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-KPARROWWIDTH - KPARROWRIGHTPADDING,(KPCellHeight - KPARROWHEIGHT)*0.5, KPARROWWIDTH, KPARROWHEIGHT);
        [jiantou setImage:[UIImage imageNamed:@"arrow_right"] forState:UIControlStateNormal];
        [cell.contentView addSubview:jiantou];
        
        UIView *lineLabel=[[UIView alloc] initWithFrame:CGRectMake(10, KPCellHeight-0.5, ScreenWidth-20, 0.5)];
        lineLabel.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel];
    }
    
    if ([[self.titleArr objectAtIndex:indexPath.row]isEqualToString:@"性别"]) {
        
        ZJSwitch *sw = [[ZJSwitch alloc] init];
        sw.frame = CGRectMake(ScreenWidth -50-15 , (KPCellHeight-25)*0.5, 50, 25);
        [sw addTarget:self action:@selector(changerSex:) forControlEvents:UIControlEventValueChanged];
        
        sw.onText = @"男";
        sw.offText = @"女";
        if ([[[dic objectForKey:@"userData"] objectForKey:@"sex"] isEqualToString:@"男"]) {
            sw.on = YES;
            sw.backgroundColor = [UIColor clearColor];
            sw.onTintColor = [UIColor colorWithRed:53/255.0 green:159/255.0 blue:234/255.0 alpha:1];
            sw.tintColor = [UIColor colorWithRed:253.00/255.0 green:129.00/255.0 blue:182.00/255.0 alpha:1];
        } else {
            sw.on = NO;
            sw.backgroundColor = [UIColor clearColor];
            sw.onTintColor = [UIColor colorWithRed:53/255.0 green:159/255.0 blue:234/255.0 alpha:1];
            sw.tintColor = [UIColor colorWithRed:253.00/255.0 green:129.00/255.0 blue:182.00/255.0 alpha:1];
        }
        [cell.contentView addSubview:sw];
        
        UIView *lineLabel=[[UIView alloc] initWithFrame:CGRectMake(10, KPCellHeight-0.5, ScreenWidth-20, 0.5)];
        lineLabel.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel];
    }
    
    if ([[self.titleArr objectAtIndex:indexPath.row]isEqualToString:@"身份"]) {
        NSString *companey = [[dic objectForKey:@"userData"] objectForKey:@"roleName"];
        CGFloat width = [companey boundingRectWithSize:CGSizeMake(ScreenWidth, 2000.f) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0]} context:nil].size.width;
        
        UILabel*shanghulabel=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-width-15, 0, width, KPCellHeight)];
        shanghulabel.text = companey;
        shanghulabel.textAlignment=NSTextAlignmentRight;
        shanghulabel.textColor=zhonghuiColor;
        shanghulabel.font=[UIFont systemFontOfSize:15.0];
        [cell.contentView addSubview:shanghulabel];
        
        UIView *lineLabel=[[UIView alloc] initWithFrame:CGRectMake(10, KPCellHeight-0.5, ScreenWidth-20, 0.5)];
        lineLabel.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel];
    }
    
    if ([[self.titleArr objectAtIndex:indexPath.row]isEqualToString:@"手机号"]) {
        NSString *phoneNum = [[dic objectForKey:@"userData"] objectForKey:@"userCode"];
        CGFloat width = [phoneNum boundingRectWithSize:CGSizeMake(ScreenWidth, 2000.f) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0]} context:nil].size.width;
        
//        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-40-width, 0, width, KPCellHeight)];
        UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(100, 0, ScreenWidth-138, KPCellHeight)];
        label.text = phoneNum;
        label.textAlignment=NSTextAlignmentRight;
        label.textColor=zhonghuiColor; label.font=[UIFont systemFontOfSize:15.0];
        [cell.contentView addSubview:label];
        
        UIButton*jiantou = [[UIButton alloc]init];
        jiantou.frame = CGRectMake(ScreenWidth-KPARROWWIDTH - KPARROWRIGHTPADDING,(KPCellHeight - KPARROWHEIGHT)*0.5, KPARROWWIDTH, KPARROWHEIGHT);
        [jiantou setImage:[UIImage imageNamed:@"arrow_right"] forState:UIControlStateNormal];
        [cell.contentView addSubview:jiantou];
       
        
        UIView *lineLabel=[[UIView alloc] initWithFrame:CGRectMake(10, KPCellHeight-0.5, ScreenWidth-20, 0.5)];
        lineLabel.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel];
    }
    
    if ([[self.titleArr objectAtIndex:indexPath.row]isEqualToString:@"所属品牌"]) {
        NSString *companey = [[dic objectForKey:@"userData"] objectForKey:@"groupName"];
        CGFloat width = [companey boundingRectWithSize:CGSizeMake(ScreenWidth, 2000.f) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17.0]} context:nil].size.width;
        
        UILabel*shanghulabel=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-width-15, 0, width, KPCellHeight)];
        shanghulabel.text = companey;
        shanghulabel.textAlignment=NSTextAlignmentRight;
        shanghulabel.textColor=zhonghuiColor;
        shanghulabel.font=[UIFont systemFontOfSize:15.0];
        [cell.contentView addSubview:shanghulabel];
        
        
        
        
        UIView *lineLabel=[[UIView alloc] initWithFrame:CGRectMake(10, KPCellHeight-0.5, ScreenWidth-20, 0.5)];
        lineLabel.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel];

    }
    
    return cell;
}
-(void)changerSex:(UISwitch*)sender{
    
    if (sender.on ==YES) {
        
        self.sexStr=@"男";
    }
    if (sender.on == NO) {
        
        self.sexStr=@"女";
    }
    
    [self UpdateUserHeader];
    
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row==0) {
        return  80;
    }
    return  55;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell =(UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    if ([cell.textLabel.text isEqualToString:@"头像"]) {
        [self editPortrait];
    }
    if ([cell.textLabel.text isEqualToString:@"姓名"]) {
        ChangeUserNameController *changeName = [[ChangeUserNameController alloc] init];
        changeName.view.backgroundColor = [UIColor whiteColor];
        [self.navigationController pushViewController:changeName animated:YES];
    }
    if ([cell.textLabel.text isEqualToString:@"手机号"]) {
        ChangePhoneNumController *changePhone = [[ChangePhoneNumController alloc] init];
        changePhone.purPhoneNum = [dic objectForKey:@"userCode"];
        [self.navigationController pushViewController:changePhone animated:YES];
    }
}

#pragma mark portraitImageView getter
#define ORIGINAL_MAX_WIDTH 640

- (void)editPortrait {
    
    NSUserDefaults *user11 = [NSUserDefaults standardUserDefaults];
    NSString* Token11 = [user11 objectForKey:@"tokenId"];
    NSMutableDictionary *params11 = [NSMutableDictionary new];
    [params11 setValue:Token11 forKey:@"tokenId"];
    [params11 setValue:@"member" forKey:@"uploadType"];
//     [params11 setValue:@"other" forKey:@"uploadType"];   //staff
//    DLog(@"%@", params11);
    [HttpRequest requestData1:@"Common/GetUpyunFormParams" params:params11 success:^(BOOL isSuccess, SeverData *severDataDict) {
         NSLog(@"GetUpyunFormParams ==%@",severDataDict.dataDict);
//        plistFileName(@"GetUpyunFormParams");
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSLog(@"%@",severDataDict.dataDict);
                NSString *policy=[severDataDict.dataDict objectForKey:@"policy"];
                NSString *signature=[severDataDict.dataDict objectForKey:@"signature"];
                NSString *action=[severDataDict.dataDict objectForKey:@"action"];
                self.policy = policy;
                self.signature = signature;
                self.action = action;

            }else{
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
            }
            
        } else {
            [MBProgressHUD hideProgressHUDInternal:self.view];
            NSString *subStr = [severDataDict.dataDict objectForKey:@"ResultString"];
            [MBProgressHUD showTextHudSub:subStr view:self.view];
        }
        
    }];
    
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    
    
    NSLog(@"%@",editedImage);
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
        [MBProgressHUD hideProgressHUDInternal:self.view];
        //设置空间名
        [UPYUNConfig sharedInstance].DEFAULT_BUCKET = @"reabamo2o"; // reabam-hd
        //设置空间表单密钥
        [UPYUNConfig sharedInstance].DEFAULT_PASSCODE = @"s8CBJl6rV+IkSWquaRTBdLKjAbo="; // s8CBJl6rV+IkSWquaRTBdLKjAbo=
        //        // 配置upyun
        __block UpYun *uy = [[UpYun alloc] init];
    
        // 上传至upyun
        uy.successBlocker = ^(NSURLResponse *response, id responseData){
            [MBProgressHUD hideProgressHUDInternal:self.view];
            //            NSLog(@"%@",[responseData objectForKey:@"url"]);
            //            DLog(@"上传成功");
            headImage=[responseData objectForKey:@"url"];
            // 上传成功之后更新到服务器
            [self UpdateUserHeader];
        };
        
        uy.failBlocker = ^(NSError *error){
            NSLog(@"%@", error);
            [MBProgressHUD hideProgressHUDInternal:self.view];
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"上传失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
//            DLog(@"-----%@",error);
        };
        
        uy.progressBlocker = ^(CGFloat percent, long long requestDidSendBytes) {
            
        };
        
        uy.policyBlocker = ^() {
//            DLog(@"498 == %@", self.policy);
            return self.policy;
        };
        // 如果 signature 由服务端生成, 服务端只需要将 policy 和 密钥 拼接之后进行 MD5, 否则就不用初始化signatureBlocker
        uy.signatureBlocker = ^(NSString *policy) {
//            DLog(@"502 == %@", self.signature);
            return self.signature;
        };
        
        [uy uploadFile:self.setImage  saveKey:[self getSaveKey]];
        
        //上传成功之后设置图片
        [imageView setImage:self.setImage forState:UIControlStateNormal];
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        [MBProgressHUD hideProgressHUDInternal:self.view];
    }];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        [MBProgressHUD showIndeterminateHudSub:@"" delay:30 view:self.view];
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, ScreenWidth, ScreenWidth) limitScaleRatio:1];
        NSLog(@"%@",portraitImg);
        self.sendImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        self.setImage = portraitImg;
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            
        }];
    }];
}

-(void)UpdateUserHeader{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:headImage forKey:@"headImage"];
    [params setValue:self.sexStr forKey:@"sex"];
//    DLog(@"params == %@", params);
    [MBProgressHUD showIndeterminateHudSub:@"" delay:30 view:self.view];
    [HttpRequest requestData1:@"Common/UpdateUser" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"33333333====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserInfo" object:nil];
//                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
//                [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
            }else{
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
            }
            
        }
        else
        {
            [MBProgressHUD hideProgressHUDInternal:self.view];
            [MBProgressHUD showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return nil;
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}


-(void)idname{

    UIActionSheet *ac = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"用户相册", nil];
    [ac showInView:self.view];
    
}




-(NSString * )getSaveKey {
    /**
     *	@brief	方式1 由开发者生成saveKey
     */
//    NSDate *d = [NSDate date];
//    return [NSString stringWithFormat:@"/%d/%d/%.0f.png",[self getYear:d],[self getMonth:d],[[NSDate date] timeIntervalSince1970]];
    
    return [NSString stringWithFormat:@"/%@.jpg", [self getDateString]];
    
    /**
     *	@brief	方式2 由服务器生成saveKey
     */
    //    return [NSString stringWithFormat:@"/{year}/{mon}/{filename}{.suffix}"];
    
    /**
     *	@brief	更多方式 参阅 http://wiki.upyun.com/index.php?title=Policy_%E5%86%85%E5%AE%B9%E8%AF%A6%E8%A7%A3
     */
    
}

- (NSString *)getDateString {
    NSDate *curDate = [NSDate date];//获取当前日期
    NSDateFormatter *formater = [[ NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy/MM/dd"];//这里去掉 具体时间 保留日期
    NSString * curTime = [formater stringFromDate:curDate];
    curTime = [NSString stringWithFormat:@"%@/%.0f", curTime, [curDate timeIntervalSince1970]];
    return curTime;
}

-(UIImage *)imageCompress:(UIImage *)image
{
    UIImage *comImage=image;
    NSData * sendImageData = UIImageJPEGRepresentation(comImage, 1.0);
    NSUInteger sizeOrigin = [sendImageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    
    if (sizeOriginKB >800) {
        float a = 80.0000;
        float b = (float)sizeOriginKB;
        float q = sqrtf(a / b);
        
        CGSize sizeImage = [comImage size];
        CGFloat widthSmall = sizeImage.width * q;
        CGFloat heighSmall = sizeImage.height * q;
        CGSize sizeImageSmall = CGSizeMake(widthSmall, heighSmall);
        
        UIGraphicsBeginImageContext(sizeImageSmall);
        CGRect smallImageRect = CGRectMake(0, 0, sizeImageSmall.width, sizeImageSmall.height);
        [image drawInRect:smallImageRect];
        UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        NSData *dataImage = UIImageJPEGRepresentation(smallImage, 1.0);
        sendImageData = dataImage;
        NSLog(@"11111111%f",sizeImageSmall.width);
        NSLog(@"11111111%f",sizeImageSmall.height);
        comImage= smallImage;
        // [_imageview1.image retain];
    }
    return comImage;
}

@end
